/*
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */
package com.xflib.framework.util;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.xflib.framework.log.StreamGobbler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * SSH Util
 *
 * @author koradji@163.com
 * @date 2023/10/24
 *
 * Usage：
 *   SshUtil.create(host, port, username, password)
 *          .open()
 *          .exec("cmd")
 *          .close();
 */
public class SshUtil {
    private static Logger logger = LoggerFactory.getLogger(SshUtil.class);

    public int getExitStatus() {
        return exitStatus;
    }

    private boolean debug=false;
    private int exitStatus;
    private Session session;
    private String host;
    private int port;
    private String username;
    private String password;
//    private CommandLineCallable<String> buffer=new CommandLineConsole();

    public static SshUtil create(String host, int port, String username, String password/*, CommandLineCallable<String> output*/) throws JSchException {
        SshUtil sshCommandExecutor=new SshUtil();
        sshCommandExecutor.host=host;
        sshCommandExecutor.port=port;
        sshCommandExecutor.username=username;
        sshCommandExecutor.password = password;
        return sshCommandExecutor;
    }

    public SshUtil open() throws JSchException {
        long startTime = System.currentTimeMillis();
        StreamGobbler.appendWithDebug(this.logger,
                String.format("[INFO] connecting %s@%s:%d", username, host, port));
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            //int timeout = 30000;
            //session.setTimeout(timeout);
            session.connect();
        }finally {
            StreamGobbler.appendWithDebug(this.logger,
                    String.format("[INFO] connected %s and cost time %.1fs.", session.isConnected()?"success":"failed",
                            (System.currentTimeMillis() - startTime) / 1000.0 ));
        }
        return this;
    }

    public void close(){
        long startTime = System.currentTimeMillis();
        StreamGobbler.appendWithDebug(this.logger, String.format("[INFO] disconnecting %s@%s:%d", username, host, port));

        try {
            session.disconnect();
        } finally {
            StreamGobbler.appendWithDebug(this.logger,
                    String.format("[INFO] disconnected %s and cost time: %.1fs.",
                            !session.isConnected()?"success":"failed",
                            (System.currentTimeMillis() - startTime) / 1000.0 ));
        }

    }

//    public SshUtil exec(String command) throws JSchException {
//        return this.exec(command/*,this.defaultOutput*/);
//    }
    public SshUtil exec(String command) throws JSchException, InterruptedException, IOException {
        long startTime = System.currentTimeMillis();

        if(session.isConnected()) {
            StreamGobbler.appendWithDebug(this.logger,
                    String.format("[INFO] Exec: %s", command));

            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setPty(false);
            channelExec.setCommand(command);
            channelExec.setErrStream(System.err);
            channelExec.connect();

            try {
                TimeUnit unit = TimeUnit.MINUTES;
                long timeout = 15;
                // any error message?
                StreamGobbler errorGobbler = new StreamGobbler(channelExec.getErrStream(), "ERROR");
                errorGobbler.setDeBug(this.debug).setTimerOut(unit.toMillis(timeout));
                // any output?
                StreamGobbler outputGobbler = new StreamGobbler(channelExec.getInputStream(), "OUTPUT");
                outputGobbler.setDeBug(this.debug).setTimerOut(unit.toMillis(timeout));

                // kick them off
                errorGobbler.start();
                outputGobbler.start();

                outputGobbler.join();
                errorGobbler.join();
//            } finally {
//
//            }
//
//
//
//            try (
//                    InputStream inputStream = channelExec.getInputStream();
//                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))
//            ) {
//                String line;
//                while ((line = reader.readLine()) != null) {
//                    buffer.appendBuffer(line, true);//this.debug);
//                    if (buffer.isDone()) {
//                        break;
//                    }
//                }
//            } catch (Exception e) {
//                buffer.setError(e);
            } finally {
                //try{Thread.sleep(1000);}catch(Exception ee){}
                this.exitStatus = channelExec.getExitStatus();
                //channelExec.disconnect();
                if(!channelExec.isClosed()){
                    channelExec.disconnect();
                }

                //buffer.setDone(true);
                StreamGobbler.appendWithDebug(this.logger,
                        String.format("[%s] Exec Exit %d, Total Cost time: %.1fs", this.exitStatus==0?"INFO":"ERROR",
                                this.exitStatus, (System.currentTimeMillis() - startTime) / 1000.0));
            }
        }

        return this;
    }

    public SshUtil setDebug(boolean debug) {
        this.debug = debug;
//        this.buffer.setDebug(debug);
        return this;
    }

//    public SshUtil setBuffer(CommandLineCallable<String> buffer) {
////        this.buffer = buffer;
//        return this;
//    }
}
